<?php

namespace app\admin\controller\disassemble;

use addons\aliocr\library\Aliocr;
use app\admin\model\Disassemble;
use app\api\model\wddj\Chat;
use app\api\model\wddj\trailer\CancellationLogs;
use app\common\controller\Backend;
use app\common\model\User;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\api\model\wddj\trailer\Order as trailerOrder;
/**
 * 回收订单
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\disassemble\Order
     */
    protected $model = null;
    /**
     * 是否开启数据限制
     * 支持auth/personal
     * 表示按权限判断/仅限个人
     * 默认为禁用,若启用请务必保证表中存在admin_id字段
     */
    protected $dataLimit = true;

    /**
     * 数据限制字段
     */
    protected $dataLimitField = 'end_adminid';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\disassemble\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("genderdataList", $this->model->getGenderdataList());
        $this->view->assign("isSanyuanList", $this->model->getIsSanyuanList());
        $this->view->assign("isDivingList", $this->model->getIsDivingList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $price = str_replace('?addtabs=1','',$this->request->get('price'));
            if($price == 1)
            {
                $list = $this->model
                    ->with(['user','disassemble'])
                    ->where($where)
//                    ->whereRaw('find_in_set(:id,order.store_admins)',['id'=>$this->auth->id])
                    ->where(['order.status'=>0])
                    ->order($sort, $order)
                    ->paginate($limit);
            }else{
                $list = $this->model
                    ->with(['user','disassemble'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            }
            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['nickname']);
				$row->getRelation('disassemble')->visible(['name','tags']);


                if(!empty($row->price_json))
                {
                    foreach ($row->price_json as $json)
                    {
                        if($json['admin_id'] == $this->auth->id)
                            $row->now_price = $json['price'];
                    }
                }else{
                    $row->now_price = '暂未报价';
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
//            if($row->end_adminid != $this->auth->id)
//                $this->error('权限不足');
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        if(!isset($params['is_diving']) && $row->status <= 1)
            $this->error('请先开始验车');
        if(!isset($params['is_diving']))
        {
            //如果填写了验车结束时间，自动结束验车
            if($params['endtime'])
            {
                if(strtotime($params['endtime']) <= $row->begintime)
                    $this->error('结束时间不合法');
                $params['status'] = 3;
            }
            $params['end_price'] = !$params['end_price'] ? $row->end_price : $row->end_price+$params['end_price'];
        }else{
            if($params['is_diving'] != $row->is_diving)
            {
                $temp = [0,$row->estimated_amount,$row->tuoche_amount,0];
                $params['end_price'] = bcadd(bcsub($row->end_price,$temp[$row->is_diving],2),$temp[$params['is_diving']],2);
            }
        }

        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 确认合作
     */
    public function do_price()
    {
        $params = $this->request->param();
//        if($params['remark'] <= 0)
//            $this->error('请输入有效报价');
        $order = $this->model->find($params['ids']);
        if(empty($order))
            $this->error('非法操作');
        if($order->status != 0)
            $this->error('已确认合作');
//        $price_json = $order['price_json'] ?: [];
//        $store = Disassemble::where(['admin_id'=>$this->auth->id])->field('id,name,admin_id,tags')->find();
//        $store['price'] = $params['remark'];
//        if(!empty($price_json))
//        {
//            foreach ($price_json as &$json)
//            {
//                if($json['id'] == $store['id'])
//                    $json = $store;
//            }
//        }else{
//            $price_json[] = $store;
//        }
//        $order->price_json = $price_json;
        $order->status = 1;
        $result = $order->save();
        if(!$result)
            $this->error('系统繁忙');
        //开始处理代驾/拖车订单
        if($order->is_diving == 1)
        {
            //代驾
            \app\admin\model\wddj\user\Order::where(['order_no'=>$order->out_trade_no])->update(['is_back_agree'=>1]);
        }
        if($order->is_diving == 2)
        {
            //拖车
            \app\api\model\wddj\usert\Order::where(['order_no'=>$order->tuoche_trade_no])->update(['is_back_agree'=>1]);
        }
        $this->success('合作成功');
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 开始检测
     */
    public function begin()
    {
        $ids = $this->request->param('ids');
        $data = $this->model->find($ids);
        if($data->end_status != 2)
            $this->error('请等待打款确认');
//        if($data->end_adminid != $this->auth->id)
//            $this->error('暂无权限');
        if($data->status > 1)
            $this->error('检测已开始');
        $data->status = 2;
        $data->begintime = time();
        $data->save();
        $this->success('操作成功');
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 打款
     */
    public function payment()
    {
        $ids = $this->request->param('ids');
        $data = $this->model->find($ids);
        if($data->status == 0)
            $this->error('请先确认合作');
        if($data->carer_status != 2)
            $this->error('请等待车手报价');
//        if($data->end_adminid != $this->auth->id)
//            $this->error('暂无权限');
        if($data->end_status != 0)
            $this->error('已打款，请勿重复操作');
        $data->end_status = 1;
        $data->payment_time = time();
        $data->save();
        $this->success('打款成功');
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 打款确认
     */
    public function over()
    {
        $ids = $this->request->param('ids');
        $data = $this->model->find($ids);
        if($data->status == 0)
            $this->error('厂商未确认合作');
//        if($data->end_adminid != $this->auth->id)
//            $this->error('暂无权限');
        if($data->end_status == 2)
            $this->error('请勿重复确认');

        if($data->end_status == 0)
            $this->error('请等待厂商打款');
        Db::startTrans();
        $data->end_status = 2;
        $data->save();
        //开始处理代驾/拖车订单
        if($data->is_diving == 1)
        {
            //代驾
            \app\admin\model\wddj\user\Order::where(['order_no'=>$data->out_trade_no])->update(['state'=>'pending']);
        }
        if($data->is_diving == 2)
        {
            //拖车
            \app\api\model\wddj\usert\Order::where(['order_no'=>$data->tuoche_trade_no])->update(['state'=>'pending']);
        }
        Db::commit();
        $this->success('确认成功');
    }
    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 费用确定
     */
    public function do_carer()
    {
        $ids = $this->request->param('ids');
        $type = $this->request->param('type');
        $data = $this->model->find($ids);
        if($data->is_diving != 2)
            $this->error('服务类型为拖车时可操作');
        if($data->carer_status == 2)
            $this->error('已确定，请勿重复操作');
        if($data->carer_status != 1)
            $this->error('请等待车手报价');
        $data->end_status = 1;
        $data->payment_time = time();
        $order = trailerOrder::where(['order_no'=>$data->tuoche_trade_no])->find();
        Db::startTrans();
        if($type == 'confirm')
        {
            //同意
            $data->carer_status = 2;
            $data->end_price = bcadd($data->tuoche_amount,$data->end_price,2);
            $order->is_back_agree = 3;
            $order->save();
        }else{
            //驳回
            $cancel_time = date('Y-m-d H:i:s',time());
            $update_data = array(
                'state'=>'pending',
                'cancel_time'=>$cancel_time,
                'driver_id'=>'',
                'driver_wechat_id'=>'',
                'begintime'=>0,
                'estimated_amount'=>0,
                'actual_amount'=>0,
                'pay_amount'=>0,
                'is_back_agree'=>1,
            );
            (new Chat())->where('order_id',$ids)->where('driver_wechat_id',$order->wechat_id)->delete();
            $result = $order->save($update_data);

            $cancellation_logs_data = array(
                'order_id'=>$order['id'],//订单id
                'wechat_id'=>$order->wechat_id,
                'driver_id'=>$order->id,
                'cancel_time'=>$cancel_time,
            );
            $cancellationLogsModel = new CancellationLogs();
            $cancellationLogsModel->data($cancellation_logs_data);
            $cancellationLogsModel->allowField(true)->save();
            $data->carer_status = 0;
            $data->tuoche_amount = 0;
            $data->tuoche_distance = 0;
            $data->tuoche_image = '';
        }
        $data->save();
        cache('id'.$ids.'cityId'.$order['city_id'].'orderNo'.$order['order_no'],null);
        Db::commit();
        $this->success('打款成功');
    }
}
